#include "qdebugtextview.h"

#include <QContextMenuEvent>
#include <QMenu>

QDebugTextView   *debugTextView=NULL;


static void DebugMsg(QtMsgType t,const char*buffer)
{
    if(debugTextView!=NULL)
    {
        debugTextView->insertPlainText(QString(buffer)+"\n");
    }
}



QDebugTextView::QDebugTextView(QWidget *parent) :
    QTextEdit(parent)
{
    debugTextView=this;
    qInstallMsgHandler(DebugMsg);
    setFrameStyle(QFrame::NoFrame);
    setReadOnly(true);
    setWordWrapMode(QTextOption::NoWrap);
}

void QDebugTextView::insertPlainText(const QString &text)
{
    while(this->document()->blockCount()>200)
    {
        this->moveCursor(QTextCursor::Start);
        QTextCursor c=this->textCursor();
        c.select(QTextCursor::BlockUnderCursor);
        c.removeSelectedText();
        c.deleteChar();
        this->setTextCursor(c);
    }
    this->moveCursor(QTextCursor::End);
    QTextEdit::insertPlainText(text);
}

void QDebugTextView::contextMenuEvent(QContextMenuEvent *e)
{
    QMenu *menu=this->createStandardContextMenu();

    menu->addSeparator();
    menu->addAction(tr("Clear"),this,SLOT(clear()));
    menu->exec(e->globalPos());
    delete menu;
}
